package com.chenziwen.scala.chapter08

object Scala15_Match3 {
  def main(args: Array[String]): Unit = {
    // 对象匹配
    object Square {
      def unapply(arg: Double): Option[Double] = {
        Some(math.sqrt(arg))
      }
    }

    val num: Double = 36.0
    num match {
      case Square(n) => println(n)
      case _ => println("nothing matched")
    }

    object Names {
      def unapplySeq(str: String): Option[Seq[String]] = {
        if (str.contains(",")) Some(str.split(","))
        else None
      }
    }
    val namesString = "Alice,Bob,Thomas"
    namesString match {
      case Names(first, second, third) => {
        //println("the string contains three people's names")
        // 打印字符串
        println(s"$first $second $third")
      }
      case _ => println("nothing matched")
    }

    // println中加表达式,使用$取变量名
    val x = "Hello"
    val y = "Scala"
    println(s"1 $x $y 11")

    val map = Map("A"->1, "B"->0, "C"->3)
    // 模式匹配会自动忽略匹配不上的元素
    for ( (k, 0) <- map ) {
      println(k)
    }

  }
}
